package cn.com.wxd.dao.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.dao.HibernateDao;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.user.UsersInfo;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.PageInfo;
import cn.com.wxd.common.data.KVMap;
import cn.com.wxd.common.data.KeyValue;

/**
 * Title:账号信息持久化类
 * Description:账号信息持久化类
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/5/22.
 *
 * @author WangXuDong
 * @version 1.0
 */
public class AccountDaoImpl extends HibernateDao implements AccountDao {

    private static final Logger log = LoggerFactory.getLogger(AccountDaoImpl.class);

    @Override
    public AccountInfo selectAccountsById(long id) {
        Session session = this.currentSession();
        return (AccountInfo) session.get(AccountInfo.class, id);
        //        try {
        //            AccountInfo accountInfo = (AccountInfo) session.createCriteria(AccountInfo.class)
        //                    .add(Restrictions.idEq(id))
        //                    .uniqueResult();
        //            return accountInfo;
        //        } catch (Exception e) {
        //            log.error(e.getMessage(), e);
        //        }
        //        return null;
    }

    @Override
    public AccountInfo selectAccountByUserName(String userName) {
        Session session = this.currentSession();
        AccountInfo accountInfo = (AccountInfo) session.createCriteria(AccountInfo.class)
                .add(Restrictions.eq("userName", userName))
                .uniqueResult();
        return accountInfo;
    }

    @Override
    public List<AccountInfo> selectAccounts(List<KeyValue<String, Object>> param, KVMap<String, String> order,
                                            List<String>
                                                    fuzzField, PageInfo page) {
        Session session = this.currentSession();
        List<AccountInfo> accountInfos;
        DetachedCriteria dc = DetachedCriteria.forClass(AccountInfo.class);
        if (param == null) {
            param = new ArrayList<>();
        }
        for (int i = 0; i < param.size(); i++) {
            if (fuzzField != null) {
                boolean res = false;
                for (int j = 0; j < fuzzField.size(); j++) {
                    if (param.get(i).getKey().equals(fuzzField.get(j))) {
                        res = true;
                        break;
                    }
                }
                if (res) {
                    dc.add(Restrictions
                            .ilike(param.get(i).getKey(), (String) param.get(i).getValue(), MatchMode.ANYWHERE));
                } else {
                    dc.add(Restrictions.eq(param.get(i).getKey(), param.get(i).getValue()));
                }
            } else {
                dc.add(Restrictions.eq(param.get(i).getKey(), param.get(i).getValue()));
            }

        }
        Criteria c = dc.getExecutableCriteria(session);
        if (page == null) {
            page = new PageInfo();
        }
        c = c.setFirstResult(page.getPageSize() * (page.getPageIndex() - 1)).setMaxResults(page.getPageSize());
        for (int i = 0; i < order.size(); i++) {
            if (order.getValueIndex(i).equalsIgnoreCase("DESC")) {
                c.addOrder(Order.desc(order.getKeyIndex(i)));
            } else {
                c.addOrder(Order.asc(order.getKeyIndex(i)));
            }
        }
        accountInfos = c.list();
        return accountInfos;
    }

    @Override
    public List<AccountInfo> selectAccountByuId(long userId) {
        Session session = this.currentSession();
        List accountInfos = session.createCriteria(AccountInfo.class)
                .add(Restrictions.eq("uid", userId))
                .addOrder(Order.desc("lalogTime"))
                .list();
        return accountInfos;
    }

    @Override
    public List<AccountInfo> selectAccountInfos(HashMap<String, String> param) {
        Session session = this.currentSession();

        DetachedCriteria dc = DetachedCriteria.forClass(AccountInfo.class);
        Iterator<String> iter = param.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            String value = param.get(key);
            dc.add(Restrictions.eq(key, value));
        }
        Criteria c = dc.getExecutableCriteria(session);
        return c.list();
    }

    @Override
    public void insertAccount(AccountInfo accountInfo) {
        Session session = this.currentSession();
        session.save(accountInfo);
    }

    @Override
    public void deleteAccount(String userName) {
        Session session = this.currentSession();
        session.delete(session.createCriteria(AccountInfo.class)
                .add(Restrictions.eq("userName", userName))
                .uniqueResult());
    }

    @Override
    public void updateAccountIp(String userName, String ip) {
        Session session = this.currentSession();
        AccountInfo accountInfo = (AccountInfo) session.createCriteria(AccountInfo.class)
                .add(Restrictions.eq("userName", userName))
                .uniqueResult();
        accountInfo.setLalogIp(ip);
        accountInfo.setLalogTime(DateUtil.getDatetimeStr());
        session.update(accountInfo);
    }

    @Override
    public void loginAuthority(String userName, boolean isForbidden) {
        Session session = this.currentSession();

        AccountInfo accountInfo = (AccountInfo) session.createCriteria(AccountInfo.class)
                .add(Restrictions.eq("userName", userName))
                .uniqueResult();
        if (accountInfo != null) {
            UsersInfo usersInfo = accountInfo.getUsersInfo();
            String str = "Y";
            if (!isForbidden) {
                str = "N";
            }
            usersInfo.setIsDisabled(str);
            session.update(accountInfo);
        }
    }
}
